package com.chuangke.common.express.function.math;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.type.AviatorDecimal;
import com.googlecode.aviator.runtime.type.AviatorObject;

public class MathAvgFunction extends AbstractFunction {

	
    private static final long serialVersionUID = 1373593913987658786L;

	@SuppressWarnings("unchecked")
	@Override
	public AviatorObject call(Map<String, Object> env, AviatorObject arg1) {
		List<BigDecimal> datas = (List<BigDecimal>) arg1.getValue(env);
		if (datas == null || datas.isEmpty()) {
			return new AviatorDecimal(0);
		}
		MathSumFunction sumFunction = new MathSumFunction();
		AviatorDecimal sumValue = (AviatorDecimal) sumFunction.call(env, arg1);
		BigDecimal sum = sumValue.toDecimal(env);
		return new AviatorDecimal(sum.divide(new BigDecimal(datas.size())));
	}

	@Override
	public String getName() {
		return "avg";
	}

}
